/**
 * Created by wei on 17/11/1.
 */
import React, { Component } from 'react';
import Draft from 'draft-js';
import axios from 'axios';
import PropTypes from 'prop-types';
import Dropzone from 'react-dropzone'
import "./css/publish.css";
import base from '../base.js';
import {stateToHTML} from 'draft-js-export-html';
const basePath = base().basePath;


const {
    AtomicBlockUtils,
    Editor,
    EditorState,
    RichUtils,
    convertToRaw,
} = Draft;


class Publish extends Component{

    constructor(props) {
        super(props);
        this.state = {
            editorState: EditorState.createEmpty(),
            loading: false,
            showURLInput: false,
            showUpImage: false,
            url: '',
            urlType: '',
            files: [],
            errorTip:'',
        };
        this.focus = () => this.refs.editor.focus();
        this.logState = () => {
            const content = this.state.editorState.getCurrentContent();
            console.log(convertToRaw(content));
        };
        this.onChange = (editorState) => this.setState({editorState});
        this.onURLChange = (e) => this.setState({urlValue: e.target.value});

        this.addAudio = this._addAudio.bind(this);
        this.addImage = this._addImage.bind(this);
        this.upImage = this._upImage.bind(this);
        this.addVideo = this._addVideo.bind(this);
        this.confirmMedia = this._confirmMedia.bind(this);
        this.handleKeyCommand = this._handleKeyCommand.bind(this);
        this.onURLInputKeyDown = this._onURLInputKeyDown.bind(this);
        this.close = this.close.bind(this);
    }

    close(flag){
        const {close} = this.props;

        this.setState({
            editorState: EditorState.createEmpty(),
            errorTip:'',
        });

        close(flag);
    }


    showLoading(){
        if(this.state.loading){
            return (
                <div style={{position:'absolute', top:'130px', left:'190px', zIndex:1100}}>
                    <img src="/images/loading.gif" width={40} height={40}/>
                </div>
            );
        }
    }

    componentWillReceiveProps(nextProps){
        const {visible} = nextProps;
        if(visible){
            this.focus();
        }
    }

    _handleKeyCommand(command, editorState) {
        const newState = RichUtils.handleKeyCommand(editorState, command);
        if (newState) {
            this.onChange(newState);
            return true;
        }
        return false;
    }

    _confirmMedia(e) {
        if(e)
        e.preventDefault();
        const {editorState, urlValue, urlType} = this.state;
        const contentState = editorState.getCurrentContent();
        const contentStateWithEntity = contentState.createEntity(
            urlType,
            'IMMUTABLE',
            {src: urlValue}
        );
        const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
        const newEditorState = EditorState.set(
            editorState,
            {currentContent: contentStateWithEntity}
        );

        this.setState({
            editorState: AtomicBlockUtils.insertAtomicBlock(
                newEditorState,
                entityKey,
                ' '
            ),
            showURLInput: false,
            showUpImage: false,
            urlValue: '',
        }, () => {
            setTimeout(() => this.focus(), 0);
        });
    }

    _onURLInputKeyDown(e) {
        if (e.which === 13) {
            this._confirmMedia(e);
        }
    }

    _promptForMedia(type) {
        const {editorState} = this.state;
        this.setState({
            showURLInput: true,
            showUpImage: false,
            urlValue: '',
            urlType: type,
        }, () => {
            setTimeout(() => this.refs.url.focus(), 0);
        });
    }

    _showUpImage(){
        this.setState({
            showUpImage: true,
            showURLInput: false,
            urlValue:'',
            urlType: 'image',
        })
    }

    _addAudio() {
        this._promptForMedia('audio');
    }

    _addImage() {
        this._promptForMedia('image');
    }

    _upImage() {
        this._showUpImage();
    }

    _addVideo() {
        this._promptForMedia('video');
    }

    getDefaultProps(){
        return {
            image: false,
        }
    }

    onDrop(files) {
        this.setState({
            loading:true,
        });
        let param = new FormData();
        if(files && files[0]&&files[0].name){
            param.append('file', files[0], files[0].name);
            let config = {
                headers: {'Content-Type': 'multipart/form-data'}
            }

            axios.post(basePath + "/file/upload", param, config)
                .then(response => {
                    // console.log(JSON.stringify(response));
                    if (response.data.url) {
                       this.setState({
                           urlValue: response.data.url,
                           loading:false,
                       });
                       this.confirmMedia();
                    }

                })
        }

    }

    publish(){
        this.setState({
            loading:true,
        });
        const {url, paramsGen} = this.props;
        let {editorState} = this.state;
        const contentState = editorState.getCurrentContent();
        if(!contentState.hasText()){
            this.setState({
                loading:false,
                errorTip:'请输入内容!',
            });

            return false;
        }
        let content = stateToHTML(contentState);

        console.log("content:"+content);

        var params = paramsGen(content);

        axios.post(url, params)
            .then(response => {
                this.setState({
                    loading:false,
                });
                if (response.data.result == 'SUCCESS') {
                    //刷新
                    this.close(true);
                }

            })
    }

    render(){

        const {visible, image, suspend} = this.props;

        let inputSho;
        if(suspend){
            inputSho = (
                <input size={60}
                    onChange={this.onURLChange}
                    ref="url"
                    style={styles.urlInput}
                    type="text"
                    value={this.state.urlValue}
                    onKeyDown={this.onURLInputKeyDown}
                />
            );
        }else{
            inputSho = (
                <input size={40}
                    onChange={this.onURLChange}
                    ref="url"
                    style={styles.urlInput}
                    type="text"
                    value={this.state.urlValue}
                    onKeyDown={this.onURLInputKeyDown}
                />
            );
        }

        let urlInput;
        if (this.state.showURLInput) {
            urlInput =
                <div className="dropTip" style={styles.urlInputContainer}>
                    {inputSho}
                    <button className="btn1" onMouseDown={this.confirmMedia}>
                        确定
                    </button>
                </div>;
        }

        let upImage;
        if(this.state.showUpImage){
            upImage = (
                <section>
                    <div className="dropzone">
                        <Dropzone className="drop" accept='image/*' onDrop={this.onDrop.bind(this)}>
                            <p>将图片拖到此处,或者单击此处选择图片.</p>
                        </Dropzone>
                        <div className="dropTip">
                                {
                                    this.state.files.map(f => <span>{f.name} - {f.size} bytes</span>)
                                }
                        </div>
                    </div>
                </section>)
        }

        let uploadShow;
        if(image){
            uploadShow = (
                <div style={styles.buttons}>
                    <button className="btn1" onMouseDown={this.addImage} style={{marginRight: 10}}>
                        增加网络图片
                    </button>
                    <button className="btn1" onMouseDown={this.upImage} style={{marginRight: 10}}>
                        上传本地图片
                    </button>
                    {/*<button onMouseDown={this.addVideo} style={{marginRight: 10}}>*/}
                    {/*增加视频*/}
                    {/*</button>*/}
                    {/*<button onMouseDown={this.addAudio} style={{marginRight: 10}}>*/}
                    {/*增加音频*/}
                    {/*</button>*/}
                </div>
            )
        }

        let content;

        if(suspend){
            content = (
                <div style={visible ? {display:'block'} : {display:'none'} }>
                    <div className="p-sign-in-box p-model p-fadeInUp p-animated">
                        <div style={{position:'absolute', top:'5px', right:'5px'}}>
                            <a href="javascript:void(0)" onClick={()=>this.close(false)}><img src="/images/close.png" width={20} height={20}/></a>
                        </div>
                        <div className="p-sigin-left">
                            <div className="p-signin-form p-clearfix">
                                {this.showLoading()}
                                {uploadShow}
                                {urlInput}{upImage}
                                <div style={styles.editor} onClick={this.focus}>
                                    <Editor
                                        blockRendererFn={mediaBlockRenderer}
                                        editorState={this.state.editorState}
                                        handleKeyCommand={this.handleKeyCommand}
                                        onChange={this.onChange}
                                        ref="editor"
                                    />
                                </div>

                            </div>
                            <div className="p-signin-foot p-clearfix" style={{height:'70px'}}>
                                <button className="btn1" onClick={this.publish.bind(this)} style={{float:'right', marginTop:'20px'}}>发表</button>
                            </div>
                        </div>
                    </div>
                    <div className="p-shade" style={this.state.loading ? {zIndex:1501} : {}}></div>
                </div>
            );
        }else{
            content = (
                <div style={visible ? {display:'block'} : {display:'none'} }>
                    <div className="p-sigin-left">
                        <div className="p-signin-form p-clearfix">
                            {this.showLoading()}
                            {uploadShow}
                            {urlInput}{upImage}
                            <div style={styles.editor} onClick={this.focus}>
                                <Editor
                                    blockRendererFn={mediaBlockRenderer}
                                    editorState={this.state.editorState}
                                    handleKeyCommand={this.handleKeyCommand}
                                    onChange={this.onChange}
                                    ref="editor"
                                />
                            </div>

                        </div>
                        <div className="p-signin-foot p-clearfix" style={{height:'70px'}}>
                            <span style={{fontSize:'12px', color:'red'}}>请勿发表违反国家法律,法规的内容!</span>
                            <span style={{fontSize:'12px', color:'red'}}>&nbsp;&nbsp;&nbsp;{this.state.errorTip}</span>
                            <span><button className="btn1" onClick={this.publish.bind(this)} style={{float:'right', marginTop:'2px'}}>发表</button></span>
                        </div>
                    </div>
                </div>
            );
        }

        return (
            content
        );
    };
}

Publish.propTypes = {
    visible: PropTypes.bool.isRequired,
    close: PropTypes.func.isRequired,
    paramsGen: PropTypes.func.isRequired,
    image: PropTypes.bool,
    url: PropTypes.string.isRequired,
    suspend: PropTypes.bool.isRequired,
};


function mediaBlockRenderer(block) {
    if (block.getType() === 'atomic') {
        return {
            component: Media,
            editable: false,
        };
    }

    return null;
}

const Audio = (props) => {
    return <audio controls src={props.src} style={styles.media} />;
};

const Image = (props) => {
    return <img src={props.src} style={styles.media}/>;
};

const Video = (props) => {
    return <video controls src={props.src} style={styles.media} />;
};

const Media = (props) => {
    const entity = props.contentState.getEntity(
        props.block.getEntityAt(0)
    );
    const {src} = entity.getData();
    const type = entity.getType();

    let media;
    if (type === 'audio') {
        media = <Audio src={src} />;
    } else if (type === 'image') {
        media = <Image src={src} />;
    } else if (type === 'video') {
        media = <Video src={src} />;
    }

    return media;
};

const styles = {
    root: {
        fontFamily: '\'Georgia\', serif',
        padding: 20,
        width: 600,
    },
    buttons: {
        border: '1px solid rgb(204, 204, 204)',
        marginBottom: 10,
        fontSize:'18px',
        marginTop:'20px',
        padding:'3px 6px'
    },
    urlInputContainer: {
        marginBottom: 10,
    },
    urlInput: {
        fontFamily: '\'Georgia\', serif',
        marginRight: 10,
        padding: 5,
    },
    editor: {
        border: '1px solid #ccc',
        cursor: 'text',
        minHeight: 80,
        padding: 10,
    },
    button: {
        marginTop: 10,
        textAlign: 'center',
    },
    media: {
        width: '100%',
        whiteSpace: 'initial'
    },
};

export default Publish;